using DocumentCreationSystem.Models.AgentOps;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

using AgentOpsStepType = DocumentCreationSystem.Models.AgentOps.StepType;

namespace DocumentCreationSystem.Services.AgentOps
{
    /// <summary>
    /// AgentOps工作流引擎实现 - 执行和管理工作流
    /// </summary>
    public class AgentOpsWorkflowEngine : IAgentOpsWorkflowEngine
    {
        private readonly ILogger<AgentOpsWorkflowEngine> _logger;
        private readonly IAIService _aiService;
        private readonly ConcurrentDictionary<string, AgentWorkflow> _activeWorkflows = new();
        private readonly ConcurrentDictionary<string, WorkflowExecutionContext> _executionContexts = new();
        private readonly List<IWorkflowEventListener> _eventListeners = new();
        private readonly SemaphoreSlim _executionSemaphore;

        public AgentOpsWorkflowEngine(
            ILogger<AgentOpsWorkflowEngine> logger,
            IAIService aiService)
        {
            _logger = logger;
            _aiService = aiService;
            _executionSemaphore = new SemaphoreSlim(10, 10); // 最多10个并发工作流
        }

        /// <summary>
        /// 从智能规划模板创建工作流
        /// </summary>
        public async Task<AgentWorkflow> CreateWorkflowFromTemplateAsync(PlanningTemplate planningTemplate)
        {
            try
            {
                _logger.LogInformation($"从模板创建工作流: {planningTemplate.Name}");

                var workflow = new AgentWorkflow
                {
                    Name = $"工作流_{planningTemplate.Name}",
                    Description = $"基于模板 {planningTemplate.Name} 创建的工作流",
                    Type = ConvertTemplateTypeToWorkflowType(planningTemplate.Type),
                    SourceTemplateId = planningTemplate.Id,
                    Status = WorkflowStatus.Created
                };

                // 根据模板内容创建工作流步骤
                await CreateStepsFromTemplateAsync(workflow, planningTemplate);

                // 验证工作流
                ValidateWorkflow(workflow);

                _logger.LogInformation($"工作流创建成功: {workflow.Id}, 步骤数: {workflow.Steps.Count}");
                return workflow;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"从模板创建工作流失败: {planningTemplate.Name}");
                throw;
            }
        }

        /// <summary>
        /// 执行工作流
        /// </summary>
        public async Task<WorkflowExecutionResult> ExecuteWorkflowAsync(
            string workflowId, 
            WorkflowExecutionContext executionContext,
            IProgress<WorkflowProgress>? progressCallback = null)
        {
            await _executionSemaphore.WaitAsync();
            
            try
            {
                _logger.LogInformation($"开始执行工作流: {workflowId}");

                if (!_activeWorkflows.TryGetValue(workflowId, out var workflow))
                {
                    throw new InvalidOperationException($"工作流不存在: {workflowId}");
                }

                var result = new WorkflowExecutionResult
                {
                    WorkflowId = workflowId,
                    StartTime = DateTime.Now,
                    Status = WorkflowStatus.Running,
                    TotalSteps = workflow.Steps.Count
                };

                // 更新工作流状态
                await UpdateWorkflowStatusAsync(workflow, WorkflowStatus.Running);

                // 存储执行上下文
                _executionContexts[workflowId] = executionContext;

                try
                {
                    // 按顺序执行步骤
                    for (int i = 0; i < workflow.Steps.Count; i++)
                    {
                        var step = workflow.Steps[i];
                        
                        // 检查依赖
                        if (!await CheckStepDependenciesAsync(workflow, step))
                        {
                            step.Status = StepStatus.Skipped;
                            result.SkippedSteps++;
                            continue;
                        }

                        // 报告进度
                        var progress = new WorkflowProgress
                        {
                            WorkflowId = workflowId,
                            CurrentStep = step.Name,
                            ProgressPercentage = (i * 100) / workflow.Steps.Count,
                            CompletedSteps = i,
                            TotalSteps = workflow.Steps.Count,
                            Message = $"正在执行: {step.Name}"
                        };
                        progressCallback?.Report(progress);

                        // 执行步骤
                        var stepResult = await ExecuteStepAsync(workflow, step, executionContext);
                        
                        if (stepResult.Success)
                        {
                            step.Status = StepStatus.Completed;
                            step.CompletedTime = DateTime.Now;
                            result.SuccessfulSteps++;
                        }
                        else
                        {
                            step.Status = StepStatus.Failed;
                            step.ErrorMessage = stepResult.ErrorMessage;
                            result.FailedSteps++;
                            result.Errors.Add($"步骤 {step.Name} 失败: {stepResult.ErrorMessage}");

                            // 根据配置决定是否继续
                            if (!workflow.Configuration.ContinueOnError)
                            {
                                break;
                            }
                        }

                        // 通知步骤完成事件
                        foreach (var listener in _eventListeners)
                        {
                            await listener.OnTaskCompletedAsync(workflowId, step.Id, stepResult);
                        }
                    }

                    // 确定最终状态
                    if (result.FailedSteps > 0 && !workflow.Configuration.ContinueOnError)
                    {
                        result.Status = WorkflowStatus.Failed;
                        await UpdateWorkflowStatusAsync(workflow, WorkflowStatus.Failed);
                    }
                    else
                    {
                        result.Status = WorkflowStatus.Completed;
                        await UpdateWorkflowStatusAsync(workflow, WorkflowStatus.Completed);
                    }

                    // 最终进度报告
                    progressCallback?.Report(new WorkflowProgress
                    {
                        WorkflowId = workflowId,
                        ProgressPercentage = 100,
                        CompletedSteps = workflow.Steps.Count,
                        TotalSteps = workflow.Steps.Count,
                        Message = result.Status == WorkflowStatus.Completed ? "工作流执行完成" : "工作流执行失败"
                    });
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"工作流执行异常: {workflowId}");
                    result.Status = WorkflowStatus.Failed;
                    result.Errors.Add($"执行异常: {ex.Message}");
                    await UpdateWorkflowStatusAsync(workflow, WorkflowStatus.Failed);

                    // 通知错误事件
                    foreach (var listener in _eventListeners)
                    {
                        await listener.OnWorkflowErrorAsync(workflowId, new WorkflowError
                        {
                            Message = ex.Message,
                            Exception = ex,
                            Timestamp = DateTime.Now
                        });
                    }
                }

                result.EndTime = DateTime.Now;
                
                // 通知工作流完成事件
                foreach (var listener in _eventListeners)
                {
                    await listener.OnWorkflowCompletedAsync(workflowId, result);
                }

                _logger.LogInformation($"工作流执行完成: {workflowId}, 状态: {result.Status}");
                return result;
            }
            finally
            {
                _executionSemaphore.Release();
                _executionContexts.TryRemove(workflowId, out _);
            }
        }

        /// <summary>
        /// 暂停工作流执行
        /// </summary>
        public async Task PauseWorkflowAsync(string workflowId)
        {
            if (_activeWorkflows.TryGetValue(workflowId, out var workflow))
            {
                await UpdateWorkflowStatusAsync(workflow, WorkflowStatus.Paused);
                _logger.LogInformation($"工作流已暂停: {workflowId}");
            }
        }

        /// <summary>
        /// 恢复工作流执行
        /// </summary>
        public async Task ResumeWorkflowAsync(string workflowId)
        {
            if (_activeWorkflows.TryGetValue(workflowId, out var workflow))
            {
                await UpdateWorkflowStatusAsync(workflow, WorkflowStatus.Running);
                _logger.LogInformation($"工作流已恢复: {workflowId}");
            }
        }

        /// <summary>
        /// 停止工作流执行
        /// </summary>
        public async Task StopWorkflowAsync(string workflowId)
        {
            if (_activeWorkflows.TryGetValue(workflowId, out var workflow))
            {
                await UpdateWorkflowStatusAsync(workflow, WorkflowStatus.Cancelled);
                _activeWorkflows.TryRemove(workflowId, out _);
                _logger.LogInformation($"工作流已停止: {workflowId}");
            }
        }

        /// <summary>
        /// 获取工作流状态
        /// </summary>
        public async Task<WorkflowStatusInfo> GetWorkflowStatusAsync(string workflowId)
        {
            if (_activeWorkflows.TryGetValue(workflowId, out var workflow))
            {
                return new WorkflowStatusInfo
                {
                    Id = workflow.Id,
                    Name = workflow.Name,
                    Status = workflow.Status,
                    Progress = CalculateProgress(workflow),
                    CurrentStep = GetCurrentStep(workflow),
                    StartTime = workflow.CreatedAt,
                    LastUpdated = workflow.UpdatedAt
                };
            }
            
            throw new InvalidOperationException($"工作流不存在: {workflowId}");
        }

        /// <summary>
        /// 获取工作流执行历史
        /// </summary>
        public async Task<List<WorkflowExecutionHistory>> GetExecutionHistoryAsync(string workflowId)
        {
            // 这里应该从数据库或存储中获取历史记录
            // 暂时返回空列表
            return new List<WorkflowExecutionHistory>();
        }

        /// <summary>
        /// 获取工作流性能指标
        /// </summary>
        public async Task<WorkflowMetrics> GetWorkflowMetricsAsync(string workflowId)
        {
            if (_activeWorkflows.TryGetValue(workflowId, out var workflow))
            {
                return new WorkflowMetrics
                {
                    WorkflowId = workflowId,
                    ExecutionTime = DateTime.Now - workflow.CreatedAt,
                    CompletedSteps = workflow.Steps.Count(s => s.Status == StepStatus.Completed),
                    FailedSteps = workflow.Steps.Count(s => s.Status == StepStatus.Failed),
                    TotalSteps = workflow.Steps.Count,
                    AverageStepDuration = CalculateAverageStepDuration(workflow)
                };
            }
            
            throw new InvalidOperationException($"工作流不存在: {workflowId}");
        }

        /// <summary>
        /// 获取所有活跃工作流
        /// </summary>
        public async Task<List<AgentWorkflow>> GetActiveWorkflowsAsync()
        {
            return _activeWorkflows.Values.ToList();
        }

        /// <summary>
        /// 注册工作流事件监听器
        /// </summary>
        public void RegisterEventListener(IWorkflowEventListener listener)
        {
            _eventListeners.Add(listener);
        }

        /// <summary>
        /// 移除工作流事件监听器
        /// </summary>
        public void RemoveEventListener(IWorkflowEventListener listener)
        {
            _eventListeners.Remove(listener);
        }

        // 私有辅助方法

        private WorkflowType ConvertTemplateTypeToWorkflowType(TemplateType templateType)
        {
            return templateType switch
            {
                TemplateType.CharacterPlanning => WorkflowType.CharacterPlanning,
                TemplateType.WorkflowPlanning => WorkflowType.ContentCreation,
                TemplateType.QualityControl => WorkflowType.QualityControl,
                TemplateType.ProjectManagement => WorkflowType.ProjectManagement,
                _ => WorkflowType.Custom
            };
        }

        private async Task CreateStepsFromTemplateAsync(AgentWorkflow workflow, PlanningTemplate template)
        {
            // 根据模板任务创建工作流步骤
            foreach (var task in template.Content.Tasks.OrderBy(t => t.Order))
            {
                var step = new WorkflowStep
                {
                    Name = task.Name,
                    Description = task.Description,
                    Type = ConvertTaskTypeToAgentOpsStepType(task.Type),
                    Order = task.Order,
                    EstimatedDurationMinutes = task.EstimatedMinutes,
                    Configuration = task.Parameters
                };

                workflow.Steps.Add(step);
            }

            // 如果没有任务，创建默认步骤
            if (workflow.Steps.Count == 0)
            {
                workflow.Steps.Add(new WorkflowStep
                {
                    Name = "处理模板内容",
                    Description = "处理和分析模板内容",
                    Type = AgentOpsStepType.DataProcessing,
                    Order = 1,
                    EstimatedDurationMinutes = 5
                });
            }
        }

        private AgentOpsStepType ConvertTaskTypeToAgentOpsStepType(TaskType taskType)
        {
            return taskType switch
            {
                TaskType.CreateCharacter => AgentOpsStepType.AIGeneration,
                TaskType.GenerateContent => AgentOpsStepType.AIGeneration,
                TaskType.CreateFile => AgentOpsStepType.FileOperation,
                TaskType.QualityCheck => AgentOpsStepType.QualityCheck,
                TaskType.ProcessData => AgentOpsStepType.DataProcessing,
                TaskType.UserInput => AgentOpsStepType.UserInteraction,
                TaskType.Condition => AgentOpsStepType.Condition,
                TaskType.Loop => AgentOpsStepType.Loop,
                _ => AgentOpsStepType.Custom
            };
        }

        private void ValidateWorkflow(AgentWorkflow workflow)
        {
            if (workflow.Steps.Count == 0)
            {
                throw new InvalidOperationException("工作流必须包含至少一个步骤");
            }

            // 检查步骤顺序
            var orders = workflow.Steps.Select(s => s.Order).ToList();
            if (orders.Distinct().Count() != orders.Count)
            {
                throw new InvalidOperationException("工作流步骤顺序不能重复");
            }
        }

        private async Task<bool> CheckStepDependenciesAsync(AgentWorkflow workflow, WorkflowStep step)
        {
            if (step.Dependencies.Count == 0)
                return true;

            foreach (var dependencyId in step.Dependencies)
            {
                var dependency = workflow.Steps.FirstOrDefault(s => s.Id == dependencyId);
                if (dependency == null || dependency.Status != StepStatus.Completed)
                {
                    return false;
                }
            }

            return true;
        }

        private async Task<TaskExecutionResult> ExecuteStepAsync(
            AgentWorkflow workflow, 
            WorkflowStep step, 
            WorkflowExecutionContext context)
        {
            try
            {
                _logger.LogInformation($"执行步骤: {step.Name} (类型: {step.Type})");

                step.StartTime = DateTime.Now;
                step.Status = StepStatus.Running;

                var result = new TaskExecutionResult { Success = true };

                // 根据步骤类型执行不同的逻辑
                switch (step.Type)
                {
                    case AgentOpsStepType.AIGeneration:
                        result = await ExecuteAIGenerationStepAsync(step, context);
                        break;
                    case AgentOpsStepType.FileOperation:
                        result = await ExecuteFileOperationStepAsync(step, context);
                        break;
                    case AgentOpsStepType.DataProcessing:
                        result = await ExecuteDataProcessingStepAsync(step, context);
                        break;
                    case AgentOpsStepType.QualityCheck:
                        result = await ExecuteQualityCheckStepAsync(step, context);
                        break;
                    default:
                        result = await ExecuteCustomStepAsync(step, context);
                        break;
                }

                step.ActualDurationMinutes = (int)(DateTime.Now - step.StartTime.Value).TotalMinutes;
                step.Result = result.Output;

                _logger.LogInformation($"步骤执行完成: {step.Name}, 成功: {result.Success}");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"步骤执行失败: {step.Name}");
                return new TaskExecutionResult
                {
                    Success = false,
                    ErrorMessage = ex.Message
                };
            }
        }

        private async Task<TaskExecutionResult> ExecuteAIGenerationStepAsync(WorkflowStep step, WorkflowExecutionContext context)
        {
            // 使用AI服务生成内容
            var prompt = step.Configuration.GetValueOrDefault("prompt", step.Description)?.ToString() ?? step.Description;
            var maxTokens = int.Parse(step.Configuration.GetValueOrDefault("maxTokens", "1000")?.ToString() ?? "1000");
            
            var aiResponse = await _aiService.GenerateTextAsync(prompt, maxTokens);
            
            return new TaskExecutionResult
            {
                Success = true,
                Output = aiResponse
            };
        }

        private async Task<TaskExecutionResult> ExecuteFileOperationStepAsync(WorkflowStep step, WorkflowExecutionContext context)
        {
            // 执行文件操作
            var operation = step.Configuration.GetValueOrDefault("operation", "create")?.ToString() ?? "create";
            var filePath = step.Configuration.GetValueOrDefault("filePath", "output.txt")?.ToString() ?? "output.txt";
            var content = step.Configuration.GetValueOrDefault("content", step.Result)?.ToString() ?? "";

            switch (operation.ToLower())
            {
                case "create":
                    await File.WriteAllTextAsync(filePath, content);
                    break;
                case "append":
                    await File.AppendAllTextAsync(filePath, content);
                    break;
                case "read":
                    content = await File.ReadAllTextAsync(filePath);
                    break;
            }

            return new TaskExecutionResult
            {
                Success = true,
                Output = $"文件操作完成: {operation} - {filePath}"
            };
        }

        private async Task<TaskExecutionResult> ExecuteDataProcessingStepAsync(WorkflowStep step, WorkflowExecutionContext context)
        {
            // 执行数据处理
            await Task.Delay(1000); // 模拟处理时间
            
            return new TaskExecutionResult
            {
                Success = true,
                Output = "数据处理完成"
            };
        }

        private async Task<TaskExecutionResult> ExecuteQualityCheckStepAsync(WorkflowStep step, WorkflowExecutionContext context)
        {
            // 执行质量检查
            await Task.Delay(500); // 模拟检查时间
            
            return new TaskExecutionResult
            {
                Success = true,
                Output = "质量检查通过"
            };
        }

        private async Task<TaskExecutionResult> ExecuteCustomStepAsync(WorkflowStep step, WorkflowExecutionContext context)
        {
            // 执行自定义步骤
            await Task.Delay(100);
            
            return new TaskExecutionResult
            {
                Success = true,
                Output = "自定义步骤执行完成"
            };
        }

        private async Task UpdateWorkflowStatusAsync(AgentWorkflow workflow, WorkflowStatus newStatus)
        {
            var oldStatus = workflow.Status;
            workflow.Status = newStatus;
            workflow.UpdatedAt = DateTime.Now;

            // 添加到活跃工作流列表
            if (newStatus == WorkflowStatus.Running)
            {
                _activeWorkflows[workflow.Id] = workflow;
            }
            else if (newStatus == WorkflowStatus.Completed ||
                     newStatus == WorkflowStatus.Failed ||
                     newStatus == WorkflowStatus.Cancelled)
            {
                _activeWorkflows.TryRemove(workflow.Id, out _);
            }

            // 通知状态变更事件
            foreach (var listener in _eventListeners)
            {
                await listener.OnWorkflowStatusChangedAsync(workflow.Id, oldStatus, newStatus);
            }
        }

        private int CalculateProgress(AgentWorkflow workflow)
        {
            if (workflow.Steps.Count == 0) return 0;
            
            var completedSteps = workflow.Steps.Count(s => s.Status == StepStatus.Completed);
            return (completedSteps * 100) / workflow.Steps.Count;
        }

        private string GetCurrentStep(AgentWorkflow workflow)
        {
            var runningStep = workflow.Steps.FirstOrDefault(s => s.Status == StepStatus.Running);
            if (runningStep != null) return runningStep.Name;

            var nextStep = workflow.Steps.FirstOrDefault(s => s.Status == StepStatus.Pending);
            return nextStep?.Name ?? "无";
        }

        private TimeSpan CalculateAverageStepDuration(AgentWorkflow workflow)
        {
            var completedSteps = workflow.Steps.Where(s => s.Status == StepStatus.Completed && s.ActualDurationMinutes.HasValue);
            if (!completedSteps.Any()) return TimeSpan.Zero;

            var averageMinutes = completedSteps.Select(s => s.ActualDurationMinutes!.Value).Average();
            return TimeSpan.FromMinutes(averageMinutes);
        }

        public Task<WorkflowOptimizationResult> OptimizeWorkflowAsync(string workflowId, WorkflowOptimizationStrategy optimizationStrategy)
        {
            throw new NotImplementedException();
        }
    }
}
